package me.landery.modules.sinco.rest;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import me.landery.annotation.AnonymousAccess;
import me.landery.exception.BadRequestException;
import me.landery.modules.sinco.service.AuthenticationService;
import me.landery.modules.sinco.service.dto.AuthenticationDto;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequiredArgsConstructor
@Api(tags = "应用授权管理")
@RequestMapping("/sinco/auth")
public class AuthenticationController {
    private final AuthenticationService authenticationService;

    /**
     * 获取授权token
     */
    @GetMapping("/token")
    @AnonymousAccess
    public ResponseEntity<Object> getAuthToken(@RequestParam(value = "appId") String appId, @RequestParam(value = "secretKey") String secretKey) {
        JSONObject jsonObject = new JSONObject();
        try{
            AuthenticationDto authToken = authenticationService.getAuthToken(appId, secretKey);
            jsonObject.put("code",0);
            jsonObject.put("msg","success");
            jsonObject.put("data",authToken);
            return new ResponseEntity<>(jsonObject, HttpStatus.OK);
        }catch (BadRequestException e){
            jsonObject.put("code",-1);
            jsonObject.put("msg",e.getMessage());
            return new ResponseEntity<>(jsonObject, HttpStatus.BAD_REQUEST);
        }catch (Exception e){
            jsonObject.put("code",-2);
            jsonObject.put("msg","系统异常");
            return new ResponseEntity<>(jsonObject, HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }

}
